<?php
class CommentsController extends AppController {

	var $name = 'Comments';
	var $uses = array('Comment', 'Media');
	
	function beforeFilter() {
		parent::beforeFilter();
		
		if ($this->Auth->user('role') == 'spectator')
		{
			$this->redirect('/');
		}
	}

	function add() {
		
		if (!empty($this->data))
		{
			$current_user = $this->Auth->user();
			if (!$this->check_permissions_for_task($current_user, $this->data['Comment']['task_id']))
			{
				$this->redirect('/');
			}
			
			$task = $this->Task->find('first', array(
				'fields' => array('Task.status', 'Task.id'),
				'conditions' => array('Task.id' => $this->data['Comment']['task_id'])
			));
			
			if (empty($task) || $task['Task']['status'] == 'closed')
			{
				$this->redirect('/');
			}
			
			$files = $this->data['Files'];
			unset($this->data['Files']);
			
			$this->Comment->create();
			$this->data['Comment']['user_id'] = $current_user['User']['id'];
			$this->data['Comment']['text'] = preg_replace ( '/ ?[\w:\-]+ ?= ?("[^"]+"|\'[^\']+\'|\w+)/i' , '' , $this->data['Comment']['text']);
			$this->data['Comment']['text'] = preg_replace ( '/(<script.*?script>)|(<style.*?style>)/i' , '' , $this->data['Comment']['text']);
			if ($this->Comment->save($this->data))
			{
				$media = array();
				srand(time());
				foreach($files as $file)
				{
					if ($file['error'] == 0)
					{
						$ext = explode('.', $file['name']);
						$ext = $ext[count($ext) - 1];
						$new_name = '';
						do{
							$new_name = $this->Comment->id . '-' . md5($new_name.$file['name'].rand()) . '.' . $ext;
						}while(file_exists($new_name));
						$media[] = array('Media' => array(
							'parent_id' => $this->Comment->id,
							'name' => $new_name,
							'parent_type' => 'comment',
							'alias' => $file['name']
						));
						move_uploaded_file($file['tmp_name'], WWW_ROOT.'files'.DS.$new_name);
					}
				}
				
				$this->Media->SaveAll($media);
				$this->Task->set_modified_date($task['Task']['id']);
				
				$this->redirect(array('controller' => 'tasks', 'action' => 'view', $this->data['Comment']['task_id']));
			}
			else
			{
				$this->redirect(array('controller' => 'tasks', 'action' => 'view', $this->data['Comment']['task_id']));
			}
		}
		else
		{
			$this->redirect('/');
		}
		
	}
	
}
